<template>
    <div class="personalAuth_page">
        <van-nav-bar title="个人认证" left-arrow @click-left="$router.push('/mine')" />

        <van-notice-bar :text=" '当前状态为： ' + computedAuditState" left-icon="volume-o" :scrollable="false" wrapable />

        <van-form @submit="handleSubmit">
            <van-field autocomplete="off" v-model="name" name="Name" label="姓名" placeholder="请输入姓名(必填)"
                :rules="[{ required: true, message: '未填写' }]" :readonly="disabled" required />
            <van-field autocomplete="off" v-model="idCard" name="IdCard" label="身份证号" placeholder="请输入身份证号码(必填)" :rules="[
        { required: true, message: '未填写' },
        { pattern: idPattern, message: '请输入正确身份证号码' }
        ]" :readonly="disabled" required />
            <van-field autocomplete="off" v-model="telephone" name="Telephone" label="手机号" placeholder="请输入手机号码(必填)"
                :rules="[{ required: true, message: '未填写' }]" :readonly="disabled" required />
            <van-field autocomplete="off" v-model="email" name="Email" label="邮箱" placeholder="请输入(选填)" :readonly="disabled" />
            <van-field autocomplete="off" v-model="qqNum" name="QQNum" label="QQ号" placeholder="请输入(选填)" :readonly="disabled" />
            <van-field autocomplete="off" v-model="wxNum" name="WxNum" label="微信号" placeholder="请输入(选填)" :readonly="disabled" />
            <!--  性别 -->
            <van-field autocomplete="off" name="genderId" label="性别" v-if="genderIdList.length"
                :rules="[{ required: true, message: '未选择性别' }]" required :readonly="disabled">
                <template #input>
                    <van-radio-group v-model="gender_id" direction="horizontal" style="margin-bottom: -10px"
                        :readonly="disabled">
                        <van-radio v-for="item in genderIdList" :name="item.key" :key="item.key"
                            style="margin-bottom: 10px">{{item.value}}</van-radio>
                    </van-radio-group>
                </template>
            </van-field>

            <van-field autocomplete="off" name="idCardFrontPhoto" label="上传身份证的正面" :rules="[{ required: true, message: '身份证的正面图片未上传' }]"
                :readonly="disabled" required>
                <template #input>
                    <van-uploader :delete="idCardFrontPhoto = ''" :deletable="deletable" v-model="id_card_front_photo"
                        :max-count="1" :after-read="afterRead1"
                        :preview-options="{
                          closeable: true,
                        }"
                    />
                </template>
            </van-field>

            <van-field autocomplete="off" name="idCardBackPhoto" label="上传身份证的背面" :rules="[{ required: true, message: '身份证的背面图片未上传' }]"
                :readonly="disabled" required>
                <template #input>
                    <van-uploader :delete=" idCardBackPhoto = '' " v-model="id_card_back_photo" :max-count="1"
                        :after-read="afterRead2" :deletable="deletable"
                        :preview-options="{
                          closeable: true,
                        }"
                    />
                </template>
            </van-field>
            <van-field autocomplete="off" name="Pictures" label="上传本人的近期照片" :rules="[{ required: true, message: '本人的近期照片未上传' }]"
                :readonly="disabled" required>
                <template #input>
                    <van-uploader :delete="picturesString = ''" v-model="personPictures" :max-count="1"
                        :after-read="afterRead3" :deletable="deletable"
                        :preview-options="{
                          closeable: true,
                        }"
                    />
                </template>
            </van-field>
            <div>
                <van-field autocomplete="off" readonly clickable :value="start_date" name="startingDate" label="身份证有效期的起始日期"
                    placeholder="请输入身份证有效期的起始日期(必填)" :rules="[{ required: true, message: '未填写' }]"
                    @click="handleShowStartPicker" :readonly="disabled" required />
                <van-popup v-model="showStartPicker" position="bottom">
                    <van-datetime-picker v-model="currentDate" type="date" title="选择年月日" :min-date="minDate"
                        :max-date="maxDate" @confirm="confirmStartDate" @cancel="showStartPicker = false" />
                </van-popup>
            </div>

            <!--  身份证是否为长期有效 -->
            <van-field autocomplete="off" name="isLongTime" label="身份证是否为长期有效" v-if="isLongTimeList.length"
                       :rules="[{ required: true, message: '未选择' }]" required :readonly="disabled">
              <template #input>
                <van-radio-group v-model="isLongTime" direction="horizontal" style="margin-bottom: -10px"
                                 :readonly="disabled">
                  <van-radio v-for="item in isLongTimeList" :name="item.key" :key="item.key"
                             style="margin-bottom: 10px">{{item.value}}</van-radio>
                </van-radio-group>
              </template>
            </van-field>

            <div v-if="!isLongTime">
                <van-field autocomplete="off" readonly clickable :value="end_date" name="endDate" label="身份证有效期的结束日期"
                    placeholder="请输入身份证有效期的结束日期(必填)" :rules="[{ required: true, message: '未填写' }]"
                    @click="handleShowEndPicker" :readonly="disabled" required />
                <van-popup v-model="showEndPicker" position="bottom">
                    <van-datetime-picker v-model="currentDate" type="date" title="选择年月日" :min-date="minDate"
                        :max-date="maxDate" @confirm="confirmEndDate" @cancel="showEndPicker = false" />
                </van-popup>
            </div>

            <!-- 提交   -->
            <div style="margin: 16px;">
                <van-button v-show="allUserInfo.certification_state === 0 || isUpdate" round block
                    :type="isUpdate ? 'danger' : 'info'">
                    {{isUpdate ? '确定修改' : '提交'}}</van-button>
            </div>
        </van-form>

        <van-overlay :show="privacyPwdOverlayShow" :lock-scroll="true">
            <div class="overlay-wrapper">
                <div class="overlay-block">
                    <van-form class="pwd-form" ref="pwdForm">
                        <div class="title">请输入隐私密码</div>
                        <van-field autocomplete="off" v-model="privacyPwd" style="text-align:center;" placeholder="请输入隐私密码"
                            :rules="[{required: true,message: ''}]" />
                        <div style="text-align: center; margin-top: .5rem;">
                            <van-button style="margin:10px;width:65px;" size="small" type="info"
                                @click="privacyPwdVerify()">确认
                            </van-button>
                            <van-button style="margin:10px;width:65px;" size="small" @click="cancelVerify()">取消
                            </van-button>
                        </div>
                    </van-form>
                </div>
            </div>
        </van-overlay>
    </div>
</template>

<script>
import {Toast, Overlay} from 'vant'
import {mapGetters} from 'vuex'
import auditState from '../../constants/auditState'
import {idCardReg} from '../../constants/comUtils'
import {cosUploadImg} from '@/utils/cosUpload.js'

const genderIdList = [
  {
    key: '0',
    value: '女'
  },
  {
    key: '1',
    value: '男'
  }
];

const isLongTimeList = [
  {
    key: 0,
    value: '否'
  },
  {
    key: 1,
    value: '是'
  }
];


export default {
  name: 'personalAuth',
  data() {
    return {
      idPattern: idCardReg,
      // 设计的状态
      auditState,
      // 图片预览时是否可删除,
      // 默认是可删除, 但是一旦提交认证过就不可删除
      disabled: false,
      deletable: true,
      currentState: '未认证， 请先认证！',
      isUpdate: false,

      // 表单中的值
      name: '',
      idCard: '',
      telephone: '',
      email: '',
      qqNum: '',
      wxNum: '',
      gender_id: '',
      genderIdList,
      isLongTime: 0,
      isLongTimeList,
      id_card_front_photo: [],
      // 后端需要
      idCardFrontPhoto: '',
      id_card_back_photo: [],
      // 后端需要
      idCardBackPhoto: '',
      personPictures: [],
      // 后端需要
      picturesString: '',
      start_date: '',
      end_date: '',
      showStartPicker: false,
      showEndPicker: false,
      minDate: new Date(1950, 0, 1),
      maxDate: new Date(2100, 10, 1),
      currentDate: new Date(),

      privacyPwd: '', // 隐私密码
      privacyPwdOverlayShow: true, // 隐私密码校验遮罩
      hasPrivacyPwd: false, // 是否设置了隐私密码
      oldPathUrl: '' // 上一页URL
    }
  },
  beforeRouteEnter (to, from, next){
    next(vm => {
      // 通过 `vm` 访问组件实例,将值传入oldPathUrl
      vm.oldPathUrl = from.path
    })
  },
  created() {
    // 避免刷新时，出现的bug
    // // 只有这两种情况讨论： 0、未认证;  1、认证中;  2、认证成功; 3 驳回（认证失败）
    // if (this.allUserInfo.certification_state != 0) {
    //   // 只有提交过认证后, 才请求个人认证详细信息
    //   this.$store.dispatch('getUserAuditInfo')
    //   this.$store.dispatch('getUserAllInfo')
    // }

    this.getHasPrivacyPwd()
    // 遮罩层打开时禁止滚动页面
    // document.body.addEventListener('touchmove', this.bodyScroll, {passive: false})
    // document.body.addEventListener('wheel', this.bodyScroll, {passive: false})
  },
  watch: {
    // 监视
    // 谨慎使用监视, 坑太多
    userAuditInfo: {
      deep: true,
      handler(newValue, oldVal) {
        if (JSON.stringify(newValue) != '{}') {
          // 更新状态
          if (newValue.audit_state != 3) {
            this.disabled = true
            this.deletable = false
            this.isUpdate = false
          } else {
            // 验证审核失败时
            this.disabled = false
            this.deletable = true
            this.isUpdate = true
          }
          // form表单中的值
          this.name = newValue.name
          this.idCard = newValue.card_id
          this.telephone = newValue.line_mobile
          this.email = newValue.email
          this.qqNum = newValue.qq_num
          this.wxNum = newValue.wx_num
          this.gender_id = newValue.gender ? '1' : '0'

          // 这是由于van-uploader组件渲染时， 执行了delete方法。因此使用this.$nextTick。dom渲染完后，再执行和更新状态。
          this.$nextTick(() => {
            // 需要的图片链接地址
            this.idCardFrontPhoto = newValue.positive_id
            this.idCardBackPhoto = newValue.negative_id
            this.picturesString = newValue.hand_id_card
          })

          this.id_card_front_photo.push({url: newValue.positive_id})
          this.id_card_back_photo.push({url: newValue.negative_id})
          this.personPictures.push({url: newValue.hand_id_card});

          // 若是有值，则表示不是长期的
          this.isLongTime = newValue.validity_end_eime ? 0 : 1;

          this.start_date = this.$needDateFormat(newValue.validity_start_time, 'yyyy-MM-dd');
          this.end_date = this.$needDateFormat(newValue.validity_end_eime, 'yyyy-MM-dd');

        }
      }
    }
  },
  computed: {
    ...mapGetters(['userAuditInfo', 'allUserInfo']),

    computedAuditState() {
      let result
      if (this.allUserInfo.certification_state_msg) {
        result = this.allUserInfo.certification_state_msg
      } else if (this.userAuditInfo.audit_state_desc) {
        result = this.userAuditInfo.audit_state_desc
      } else {
        result = this.currentState
      }
      return result
    }
  },
  methods: {
    // 封装函数
    async _reqUploadPicture(picture) {
      let formData = new FormData()
      formData.append('filename', picture.file)
      const img_type = 'user_certification'
      // const res = await this.$api.uploadImg.uploadPhotos(formData, img_type)
      const res = await cosUploadImg(picture.file, img_type)
      if (res.code === 200) {
        return res.data
      }
    },

    afterRead1(picture) {
      picture.status = 'uploading';
      picture.message = '上传中...';
      // async/await函数的返回结果仍是promise对象, 使用.then()取得返回值
      this._reqUploadPicture(picture).then(res => {
        if (!res) {
          Toast('图片上传失败!')
          picture.status = 'failed';
          picture.message = '上传失败';
        } else {
          picture.status = 'done';
        }
        this.idCardFrontPhoto = res
      })
    },
    afterRead2(picture) {
      picture.status = 'uploading';
      picture.message = '上传中...';
      this._reqUploadPicture(picture).then(res => {
        if (!res) {
          Toast('图片上传失败!')
          picture.status = 'failed';
          picture.message = '上传失败';
        } else {
          picture.status = 'done';
        }

        this.idCardBackPhoto = res
      })
    },
    afterRead3(picture) {
      picture.status = 'uploading';
      picture.message = '上传中...';
      this._reqUploadPicture(picture).then(res => {
        if (!res) {
          Toast('图片上传失败!')
          picture.status = 'failed';
          picture.message = '上传失败';
        } else {
          picture.status = 'done';
        }
        this.picturesString = res
      })
    },
    handleShowStartPicker() {
      this.showStartPicker = !this.disabled
    },

    handleShowEndPicker() {
      this.showEndPicker = !this.disabled
    },

    confirmStartDate(time) {
      // console.log('开始时间', this.$needDateFormat(time, 'yyyy-MM-dd') )
      this.start_date = this.$needDateFormat(time, 'yyyy-MM-dd');
      this.showStartPicker = false
    },
    confirmEndDate(time) {
      this.end_date = this.$needDateFormat(time, 'yyyy-MM-dd')
      this.showEndPicker = false
    },

    async handleSubmit(values) {
      const {Name, IdCard, Telephone, Email, QQNum, WxNum, genderId, startingDate, endDate, isLongTime} = values
      if (this.start_date.replace(/-/g, '') * 1 >= this.end_date.replace(/-/g, '') * 1 && !isLongTime) {
        Toast('法人身份证起止日期不合法，请修改！')
      } else {
        const params = {
          name: Name,
          card_id: IdCard,
          line_mobile: Telephone,
          positive_path: this.idCardFrontPhoto,
          negative_path: this.idCardBackPhoto,
          gender: Boolean(genderId * 1),
          validity_start_time: startingDate,
          validity_end_time: isLongTime ? '长期有效' : endDate,
          hand_id_card_path: this.picturesString,
          email: Email,
          qq_num: QQNum,
          wx_num: WxNum
        }
        const res = await this.$api.authentication.reqUserAuth(params)
        if (res.code === 200) {
          Toast(res.data)
          await this.$router.push('/mine')
          // 重新获取
          await this.$store.dispatch('getUserAllInfo')
        }
      }
    },

    cancelVerify() {
      // 取消隐私密码校验的话回退到上一页
      console.log('oldPathUrl', this.oldPathUrl)
      if(this.oldPathUrl && this.oldPathUrl.indexOf('privacyPwd') == -1 ) {
        this.$router.go(-1)
      } else {
        this.$router.push({name: 'mine'})
      }
    },

    privacyPwdVerify() {
      this.$refs['pwdForm']
        .validate()
        .then(() => {
          let params = {
            privacypwd: this.privacyPwd
          }

          // 查看隐私密码
          this.$api.user.privacyCheck(params).then(res => {
            if (res.code === 200 && res.data == 'true') {
              // 隐私密码正确
              this.privacyPwdOverlayShow = false
              // 只有这两种情况讨论： 0、未认证;  1、认证中;  2、认证成功; 3 驳回（认证失败）
              if (this.allUserInfo.certification_state != 0) {
                // 只有提交过认证后, 才请求个人认证详细信息
                this.$store.dispatch('getUserAuditInfo')
                this.$store.dispatch('getUserAllInfo')
              }
              // document.body.removeEventListener('touchmove', this.bodyScroll, {passive: false})
              // document.body.removeEventListener('wheel', this.bodyScroll, {passive: false})
            } else {
              Toast('隐私密码错误！')
            }
          })
        })
        .catch(e => {
          console.log(e)
        })
    },

    bodyScroll(event) {
      event.preventDefault()
    },

    // 是否设置了隐私密码
    async getHasPrivacyPwd() {
      const res = await this.$api.user.hasPrivacyPwd()
      if (res.code === 200) {
        this.hasPrivacyPwd = res.data
        if (this.hasPrivacyPwd == 'false') {
          // 未设置隐私密码
          this.$router.push({name: 'privacyPwd', params: {type: 3}})
        }
      }
    }
  },

  destroyed() {
    this.$store.dispatch('clearUserAuditInfo')
    // 解绑禁止页面滚动事件
    // document.body.removeEventListener('touchmove', this.bodyScroll, {passive: false})
    // document.body.removeEventListener('wheel', this.bodyScroll, {passive: false})
  }
}
</script>

<style lang="css" scoped>
.isCompletedAudit {
  display: none;
}

.overlay-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.overlay-block {
  display: table;
  width: 100%;
  height: 100%;
  background-color: #fff;
}

.overlay-block .title {
  margin: 0.5rem auto;
  color: #323233;
  font-weight: 500;
  font-size: 0.42667rem;
}

.overlay-block .pwd-form {
  display: table-cell;
  text-align: center;
  vertical-align: middle;
  padding: 0 8%;
}
</style>
